//
//  UULoginVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 13/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UULoginVC.h"
#import "UULoginManager.h"
#import "UUSupplierManager.h"
#import <UUFoundation/DKInputTextField.h>
#import "UUVerifyCodeVC.h"
#import "UUSupplierRegisterVC.h"
#import "AppDelegate.h"

@interface UULoginVC ()

@property (nonatomic, strong) DKInputTextField *mobileField;
@property (nonatomic, strong) UIButton *nextButton;

@end

@implementation UULoginVC

+ (BOOL)enableTranslucentNavigationBar {
    return YES;
}

- (void)loadView {
    [super loadView];
    
    self.view = [[UIControl alloc] initWithFrame:self.view.frame];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [(UIControl *)self.view addTarget:self action:@selector(tapToDismissKeyboard) forControlEvents:UIControlEventTouchUpInside];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
            
    [self setupUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (void)tapToDismissKeyboard {
    [self.mobileField resignFirstResponder];
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    
    UILabel *mobileLabel = [UILabel new];
    mobileLabel.textAlignment = NSTextAlignmentCenter;
    mobileLabel.text = @"输入手机号";
    mobileLabel.textColor = COMMON_TEXT_DARK_COLOR;
    mobileLabel.font = [UIFont systemFontOfSize:21];
    [self.view addSubview:mobileLabel];
    [mobileLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_topLayoutGuideBottom).offset(50);
        make.left.right.mas_equalTo(0);
    }];
    
    self.mobileField = [DKInputTextField new];
    self.mobileField.bottomLineColor = COMMON_TEXT_BLACK_COLOR;
    self.mobileField.showBottomLine = YES;
    self.mobileField.font = [UIFont systemFontOfSize:30];
    self.mobileField.textAlignment = NSTextAlignmentCenter;
    self.mobileField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:self.mobileField];
    [self.mobileField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(mobileLabel).offset(50);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(44);
    }];
    
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextButton.titleLabel.font = [UIFont systemFontOfSize:15];
    self.nextButton.layer.borderColor = COMMON_TEXT_DARK_COLOR.CGColor;
    self.nextButton.layer.borderWidth = 1;
    [self.nextButton setTitleColor:COMMON_TEXT_DARK_COLOR forState:UIControlStateNormal];
    [self.nextButton setTitle:@"下一步" forState:UIControlStateNormal];
    [self.nextButton addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.nextButton];
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mobileField.mas_bottom).offset(50);
        make.left.right.equalTo(self.mobileField);
        make.height.mas_equalTo(44);
    }];
    
    UIButton *agreementButton = [UIButton buttonWithType:UIButtonTypeCustom];
    NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithString:@"注册即表示同意"
                                                                                        attributes:@{
                                                                                                     NSForegroundColorAttributeName : COMMON_TEXT_BLACK_COLOR,
                                                                                                     NSFontAttributeName : [UIFont systemFontOfSize:12]
                                                                                                     }];
    [attributedTitle appendAttributedString:[[NSAttributedString alloc] initWithString:@"《合作协议条款》"
                                                                            attributes:@{
                                                                                         NSForegroundColorAttributeName : COMMON_TEXT_ORANGE_COLOR,
                                                                                         NSFontAttributeName : [UIFont systemFontOfSize:12]
                                                                                         }]];
    [agreementButton setAttributedTitle:attributedTitle forState:UIControlStateNormal];
    [agreementButton addTarget:self action:@selector(enterAgreement) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:agreementButton];
    [agreementButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_equalTo(-20);
    }];
}

- (void)enterAgreement {
    UUHybridWebVC *webVC = [UUHybridWebVC new];
    webVC.URLString = @"http://wap.ubaoche.com/app/supplier/register/protocol";
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)next {
    [self.view endEditing:YES];
    
    NSString *mobile = self.mobileField.text;
    
    if ([NSString isBlank:mobile]) {
        ShowTips(@"请输入手机号");
        return;
    }
    
    if (![mobile isPhoneNumber]) {
        ShowTips(@"请输入正确的手机号");
        return;
    }

    WEAK_SELF();
    ShowIndicator();
    [self requestVerifyCodeWithCompleteBlock:^(NSError *error) {
        if (error == nil) {
            HideIndicatorInView(weakSelf.view);
            [weakSelf enterVerifyCodeVC];
        } else {
            ShowTipsOnView(error.localizedDescription, weakSelf.view);
        }
    }];
}

- (void)enterVerifyCodeVC {
    UUVerifyCodeVC *verifyCodeVC = [UUVerifyCodeVC instanceOfAppropriate];
    verifyCodeVC.mobile = self.mobileField.text;
    WEAK_SELF();
    verifyCodeVC.codeDidInputCompleteBlock = ^(NSString *code) {
        [weakSelf loginWithMobile:weakSelf.mobileField.text code:code];
    };
    verifyCodeVC.requestVerifyCodeBlock = ^(UUVerifyCodeRequestHanlder handler) {
        [weakSelf requestVerifyCodeWithCompleteBlock:^(NSError *error) {
            handler(error);
        }];
    };
    
    [verifyCodeVC startCountdown];
    [self.navigationController pushViewController:verifyCodeVC animated:YES];
}

- (void)requestVerifyCodeWithCompleteBlock:(void (^)(NSError *error))completeBlock {
    [GetLoginManager() sendVerifyCodeWithMobile:self.mobileField.text
                                  completeBlock:completeBlock];
}

- (void)loginWithMobile:(NSString *)mobile code:(NSString *)code {
    ShowIndicatorInKeyWindow();
    [GetLoginManager() loginWithMobile:mobile
                            verifyCode:code
                         completeBlock:^(NSError *error) {
                             HideIndicatorInKeyWindow()
                             
                             if (error != nil) {
                                 if (error.code == 10000) { // 未注册
                                     UUSupplierRegisterVC *registerVC = [UUSupplierRegisterVC instanceOfAppropriate];
                                     WEAK_SELF();
                                     [registerVC setCompleteBlock:^(NSDictionary *data) {
                                         [weakSelf registerSupplierWithData:data];
                                     }];
                                     [self.navigationController pushViewController:registerVC animated:YES];
                                 } else {
                                     ShowTipsInKeyWindow(error.localizedDescription);
                                 }
                             } else {
                                 [GetAppDelegate() presentHome];
                             }
                         }];
}

- (void)registerSupplierWithData:(NSDictionary *)data {
    ShowIndicatorInKeyWindow()
    [GetSupplierManager() registerSupplierWithMobile:self.mobileField.text
                                              cityId:data[@"city_id"]
                                             company:data[@"company"]
                                             address:data[@"address"]
                                             contact:data[@"contact"]
                                       contactMobile:data[@"contact_mobile"]
                               transportationLicense:data[@"transportation_license"]
                                     businessLicense:data[@"business_license"]
                                         idCardFront:data[@"id_card_front"]
                                          idCardBack:data[@"id_card_back"]
                                       completeBlock:^(NSError *error) {
                                           HideIndicatorInKeyWindow();
                                           
                                           if (error != nil) {
                                               ShowTipsInKeyWindow(error.localizedDescription);
                                           } else {
                                               [GetAppDelegate() presentHome];
                                           }
                                       }];
}

@end
